import {
  ConnectionFailed,
  ErrorNoticeQueryKeys,
  RemoteControlNotActive,
  RemoteStartNotActive,
} from '@/constants/ErrorNoticeActions'
import { useApplianceStore } from '@/store/appliance'
import store from '@/store'
import { OPERATION_KEY, OPERATION_STATES, SETTING_REMOTE_CONTROL_LEVEL } from '@/constants/Command'
import { getActionHandlerInfo } from '@/api/event'
import { OpenNoticeActionByApiError } from '@/constants/UniEventKeys'
import { showModal, toPage } from '@/utils/mpHelper'
import type { BaseController } from '@/controller/BaseAppliance/definition'
import type { NoticeQuery } from '@/controller/common/Notice/notice'
import i18n from '@/i18n'
import type { ToParameterSettingsPayload } from '@/pages/appliance/settings/applianceSettingsView.vue'
import type { WS } from '@/utils/socket/types'
import { RemoteTypes } from '@/controller/base/remote'

// 查询通知action并触发事件
export async function triggerNoticeQuery(noticeQuery: NoticeQuery): Promise<boolean> {
  const applianceStore = useApplianceStore(store)
  const currentAppliance = applianceStore.current
  if (!currentAppliance) return false

  const { type, vib, brand } = currentAppliance

  // 获取接口返回的通知配置
  const noticeParams = [
    {
      key: noticeQuery.key,
      value: noticeQuery.value,
      brand,
      type,
      vib,
    },
  ]
  const res = await getActionHandlerInfo(noticeParams)
  const noticeInfo = res.data?.[0]
  if (!noticeInfo || !noticeInfo.action) return false

  uni.$emit(OpenNoticeActionByApiError, noticeInfo)
  return true
}

/**
 * 报错弹框
 */
export function showErrorNativeModal(options: UniNamespace.ShowModalOptions) {
  return showModal({
    confirmColor: '#007aff',
    cancelColor: '#666666',
    confirmText: i18n.global.t('APP.Common.Define.Text'),
    showCancel: false,
    ...options,
  })
}
// 触发离线弹框
export function triggerOfflineModal() {
  triggerNoticeQuery(ErrorNoticeQueryKeys[ConnectionFailed])
}
// 触发通用远程控制未开启弹框
export function triggerGeneralControlNotActiveModal() {
  triggerNoticeQuery(ErrorNoticeQueryKeys[RemoteControlNotActive])
}
// 触发远程启动未开启弹框
export function triggerRemoteStartNotActiveModal() {
  triggerNoticeQuery(ErrorNoticeQueryKeys[RemoteStartNotActive])
}
// 确认跳转远程控制等级 设置页
export async function confirmToControlLevelTips(options: { haId: string; type: string; vib: string }) {
  try {
    await showControlLevelModal()

    const { haId, type, vib } = options
    const payload: ToParameterSettingsPayload = {
      haId,
      type,
      vib,
      key: SETTING_REMOTE_CONTROL_LEVEL,
      isVirtual: false,
    }
    await toPage('/pages/appliance/settings/parameterSettings', payload)
  } catch (e) {
    console.error(e)
  }
}
// 跳转远程控制等级提示
export function showControlLevelModal() {
  return showErrorNativeModal({
    content: i18n.global.t('Appliance.RemoteHint.EnableRemoteControlRequired.Text'),
    confirmText: i18n.global.t('Appliance.RemoteHint.ToEnableRemoteControl.Text'),
    cancelText: i18n.global.t('APP.Common.Cancel.Text'),
    showCancel: true,
  })
}
// 操作频繁
export function showFrequentlyOperationModal() {
  return showErrorNativeModal({
    content: i18n.global.t('Appliance.ErrorHandler.FrequentlyOperation.Text'),
  })
}
// 开机后操作
export function showRequirePowerOnToContinueModal() {
  return showErrorNativeModal({
    content: i18n.global.t('Appliance.ErrorHandler.PowerOnConfirm.Text'),
    confirmText: i18n.global.t('APP.Common.Define.Text'),
    cancelText: i18n.global.t('APP.Common.Cancel.Text'),
    showCancel: true,
  })
}
export function confirmPowerOn(control: BaseController.Control) {
  return showRequirePowerOnToContinueModal().then(async () => {
    // await showLoading(() => {
    return new Promise<void>((resolve, reject) => {
      control.store.togglePowerState()
      try {
        const onceObserve = {
          matcher: (msg: WS.MessageItem) => msg.key === OPERATION_KEY,
          handler: (msg: WS.MessageItem) => {
            // inhouse取value字段 oem取displayvalue字段
            const isReady =
              control.remote.remoteType === RemoteTypes.Inhouse
                ? msg.value === OPERATION_STATES.READY
                : msg.displayvalue === OPERATION_STATES.READY

            // ready状态表示开机完成 继续下发后续操作
            if (isReady) {
              control.remote.removeBatchObserve(onceObserve as any)
              setTimeout(() => resolve(), 500)
            }
          },
        }
        control.remote.addBatchObserve(onceObserve)
      } catch (e) {
        reject(e)
      }
    })
    // }, i18n.global.t('APP.Common.Submitting.Text'))
  })
}
// 未选程序
export function showNoProgramModal() {
  return showErrorNativeModal({
    content: i18n.global.t('Appliance.ErrorHandler.SelectProgramRequired.Text'),
  })
}
// 不支持预约
export function showOrderNotSupported() {
  return showErrorNativeModal({
    content: i18n.global.t('Appliance.ErrorHandler.OrderNotAvailable.Text'),
  })
}
// 门打开 且 远程启动未开启
export function showDoorOpenedRemoteStartDisabledModal() {
  return showErrorNativeModal({
    content: i18n.global.t('Appliance.ErrorHandler.CloseDoorAndEnableRemoteStartRequired.Text'),
  })
}
// 本地控制
export function showLocalOperatingModal() {
  return showErrorNativeModal({
    content: i18n.global.t('Appliance.ErrorHandler.LocalOperating.Text'),
  })
}
// 童锁已打开
export function showChildLockEnabledModal() {
  return showErrorNativeModal({
    content: i18n.global.t('Appliance.ErrorHandler.ChildLockEnabled.Text'),
  })
}
